import { asyncRoutes, constantRoutes, getAsyncRoutes } from '@/router'
import Layout from '@/layout'
import sysMenuApi from '@/api/sysMenu'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * 生成扁平化机构路由(仅两级结构)
 * @param {允许访问的路由Tree} accessRoutes
 * 路由基本机构:
 * {
 *   name: String,
 *   path: String,
 *   component: Component,
 *   redirect: String,
 *   children: [
 *   ]
 * }
 */
function generateFlatRoutes(accessRoutes) {
  let flatRoutes = []

  for (let item of accessRoutes) {
    let childrenFflatRoutes = []
    if (item.children && item.children.length > 0) {
      childrenFflatRoutes = castToFlatRoute(item.children, '')
    }

    // 一级路由是布局路由,需要处理的只是其子路由数据
    flatRoutes.push({
      name: item.name,
      path: item.path,
      component: item.component,
      redirect: item.redirect,
      children: childrenFflatRoutes
    })
  }

  return flatRoutes
}

/**
 * 将子路由转换为扁平化路由数组（仅一级）
 * @param {待转换的子路由数组} routes
 * @param {父级路由路径} parentPath
 */
function castToFlatRoute(routes, parentPath, flatRoutes = []) {
  for (let item of routes) {
    if (item.children && item.children.length > 0) {
      if (item.redirect && item.redirect !== 'noRedirect') {
        flatRoutes.push({
          name: item.name,
          path: (parentPath + '/' + item.path).substring(1),
          redirect: item.redirect,
          meta: item.meta
        })
      }
      castToFlatRoute(item.children, parentPath + '/' + item.path, flatRoutes)
    } else {
      flatRoutes.push({
        name: item.name,
        path: (parentPath + '/' + item.path).substring(1),
        component: item.component,
        meta: item.meta
      })
    }
  }

  return flatRoutes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  /**
   * 获取本地路由
   * @param commit
   * @param roles
   * @returns {Promise<unknown>}
   */
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      let flatRoutes = generateFlatRoutes(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(flatRoutes)
    })
  },
  /**
   * 通过接口获取后台接口
   * @param commit
   * @param roles
   * @returns {Promise<unknown>}
   */
  getRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      sysMenuApi.listMy(1).then(res => {
        let routes = getAsyncRoutes()
        generaMenu(routes, res.data, true)
        let flatRoutes = generateFlatRoutes(routes)
        commit('SET_ROUTES', routes)
        resolve(flatRoutes)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
function generaMenu(routes, data, level) {
  data.forEach(item => {
    let component
    if (level) {
      if (item.componentPath) {
        //component = require(`@/layout/${item.componentPath}`).default
        component = Layout
      } else {
        component = Layout
      }
    } else {
      if (item.componentPath) {
        component = require(`@/views/${item.componentPath}`).default
      }
    }
    const menu = {
      path: `${item.path}`,
      component,
      //name: item.name,
      redirect: level ? 'noRedirect' : '',
      hidden: item.hidden,
      meta: {  icon: item.icon },
      children: []
    }
    if (item.children.length !== 0) {
      generaMenu(menu.children, item.children, false)
    }else {
      menu.children.push({
        path: `${item.path}`,
        component: () => import(`@/views/${item.componentPath}`).default,
        name: item.name,
        meta: { title: item.title }
      })
    }
    if (menu.children.length === 0) {
      delete menu.children
    }
    routes.push(menu)
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
